<script setup lang="ts">
import { ref, computed } from 'vue'
import { useAuthStore } from '@/stores/auth'
import { useRouter } from 'vue-router'

const router = useRouter()
const auth = useAuthStore()

const login_id = ref('')
const email = ref('')
const password = ref('')
const name = ref('')
const nickname = ref('')
const phone = ref('')
const gender = ref('')
const birthdate = ref('')
const partner_code = ref('')

const rules = {
  login_id: (v: string) => /^\w{6,20}$/.test(v),
  email: (v: string) => /.+@.+\..+/.test(v),
  password: (v: string) => v.length >= 8,
  partner_code: (v: string) => /^[A-Z0-9]{6,10}$/.test(v),
}

const canSubmit = computed(
  () =>
    rules.login_id(login_id.value) &&
    rules.email(email.value) &&
    rules.password(password.value) &&
    rules.partner_code(partner_code.value),
)

async function onSubmit() {
  if (!canSubmit.value) return
  const ok = await auth.register({
    login_id: login_id.value.trim(),
    email: email.value.trim(),
    password: password.value,
    name: name.value || undefined,
    nickname: nickname.value || undefined,
    phone: phone.value || undefined,
    gender: gender.value || undefined,
    birthdate: birthdate.value || undefined,
    partner_code: partner_code.value,
  })

  if (ok) {
    // 确保用户状态完整后再跳转
    const isStateComplete = await auth.ensureUserState()
    if (isStateComplete) {
      router.push('/home')
    } else {
      // 如果状态不完整，提示用户重新登录
      auth.error = '가입 완료, 설정 완료를 위해 다시 로그인해주세요'
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    }
  }
}
</script>

<template>
  <div class="auth-wrap">
    <div class="card">
      <div class="brand">라이브팬</div>

      <div class="form grid">
        <div class="col">
          <label>로그인 ID</label>
          <input 
            v-model="login_id" 
            placeholder="영문, 숫자, 밑줄 6-20자"
            :class="{ error: login_id && !rules.login_id(login_id) }"
          />
          <small v-if="login_id && !rules.login_id(login_id)" class="error-text">
            로그인 ID는 영문, 숫자, 밑줄(_)로 6-20자여야 합니다
          </small>
        </div>
        <div class="col">
          <label>이메일</label>
          <input 
            v-model="email" 
            placeholder="이메일"
            :class="{ error: email && !rules.email(email) }"
          />
          <small v-if="email && !rules.email(email)" class="error-text">
            올바른 이메일 형식을 입력해주세요
          </small>
        </div>
        <div class="col">
          <label>비밀번호</label>
          <input 
            v-model="password" 
            type="password" 
            placeholder="최소 8자"
            :class="{ error: password && !rules.password(password) }"
          />
          <small v-if="password && !rules.password(password)" class="error-text">
            비밀번호는 최소 8자 이상이어야 합니다
          </small>
        </div>
        <div class="col">
          <label>이름</label>
          <input v-model="name" />
        </div>
        <div class="col">
          <label>닉네임</label>
          <input v-model="nickname" />
        </div>
        <div class="col">
          <label>휴대폰 번호</label>
          <input v-model="phone" />
        </div>
        <div class="col">
          <label>성별</label>
          <select v-model="gender">
            <option value="">선택 안함</option>
            <option value="male">남성</option>
            <option value="female">여성</option>
            <option value="other">기타</option>
          </select>
        </div>
        <div class="col">
          <label>생일</label>
          <input v-model="birthdate" type="date" />
        </div>
        <div class="col">
          <label>추천 코드 *</label>
          <input
            v-model="partner_code"
            placeholder="6-10자 대문자와 숫자"
            required
            :class="{ error: partner_code && !rules.partner_code(partner_code) }"
          />
          <small v-if="partner_code && !rules.partner_code(partner_code)" class="error-text">
            추천 코드 형식이 올바르지 않습니다. 6-10자 대문자와 숫자여야 합니다
          </small>
        </div>
      </div>

      <div class="actions">
        <button class="btn primary" :disabled="!canSubmit || auth.loading" @click="onSubmit">
          {{ auth.loading ? '회원가입 중...' : '회원가입' }}
        </button>
        <router-link class="btn ghost" to="/login">로그인으로 돌아가기</router-link>
        <p v-if="auth.error" class="error">{{ auth.error }}</p>
      </div>
    </div>
  </div>
</template>

<style scoped>
.auth-wrap {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: linear-gradient(180deg, #f8fafc, #eef2ff);
}
.card {
  width: 760px;
  max-width: 96vw;
  background: #fff;
  border-radius: 16px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.08);
  padding: 32px;
}
.brand {
  font-weight: 800;
  font-size: 22px;
  letter-spacing: 4px;
  color: #6366f1;
  text-align: center;
  margin-bottom: 18px;
}
.form.grid {
  display: grid;
  grid-template-columns: repeat(2, minmax(0, 1fr));
  gap: 12px;
}
.col {
  display: flex;
  flex-direction: column;
  gap: 8px;
}
label {
  font-size: 13px;
  color: #374151;
}
input,
select {
  height: 42px;
  border: 1px solid #e5e7eb;
  border-radius: 10px;
  padding: 0 12px;
  outline: none;
  transition: 0.2s;
}
input:focus,
select:focus {
  border-color: #ef476f;
  box-shadow: 0 0 0 3px rgba(239, 71, 111, 0.15);
}
.actions {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 16px;
}
.btn {
  height: 44px;
  border-radius: 10px;
  border: none;
  cursor: pointer;
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-top: 8px;
  text-decoration: none;
}
.btn.primary {
  background: #ef476f;
  color: #fff;
  padding: 0 16px;
}
.btn.primary:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}
.btn.ghost {
  border: 1px solid #e5e7eb;
  color: #111827;
  background: #fff;
  padding: 0 16px;
}
.error {
  color: #ef476f;
  margin-left: auto;
}
input.error {
  border-color: #ef476f;
  box-shadow: 0 0 0 3px rgba(239, 71, 111, 0.15);
}
.error-text {
  color: #ef476f;
  font-size: 12px;
  margin-top: 4px;
}
small {
  display: block;
}
@media (max-width: 640px) {
  .form.grid {
    grid-template-columns: 1fr;
  }
}
</style>
